//
//  SuggestionViewController.m
//  com.modada.new
//
//  Created by ferver7 on 2019/5/12.
//  Copyright © 2019 ferver7. All rights reserved.
//

#import "SuggestionViewController.h"
#import "PostImageCell.h"
#import "ImagePostTool.h"
@interface SuggestionViewController ()
@property (weak, nonatomic) IBOutlet UILabel *storeNameLabel;
@property (weak, nonatomic) IBOutlet PlaceholderTextView *desTv;
@property (weak, nonatomic) IBOutlet PostImageCell *postImageModule;
@property (nonatomic,strong) AxcUI_ActivityHUD * axcUI_ActivityHUD;
@property (nonatomic,strong) NSMutableArray * postImgsURL;//上传的图片
@property (nonatomic,assign) CGFloat postCellHeight;
@end

@implementation SuggestionViewController
- (IBAction)sureSubmit:(id)sender {
    if(self.desTv.text.length <1){
        [AxcUI_Toast AxcUI_showCenterWithText:@"请输入反馈意见"];
        return;
    }
    
    if (self.postImgsURL.count == 0) {
        [AxcUI_Toast AxcUI_showCenterWithText:@"至少上传一张意见图片"];
        return;
    }
    NSMutableDictionary * requestInfo = [[NSMutableDictionary alloc]init];
    setDickeyobj(requestInfo, [AppUserBaseModel sharedUserData].storeName, @"complaintStoreName");
     setDickeyobj(requestInfo, [AppUserBaseModel sharedUserData].uid, @"complaintStoreid");
     setDickeyobj(requestInfo, self.desTv.text, @"content");
    NSString* images ;
    for (NSString * imageUrl in self.postImgsURL) {
        if (images.length == 0) {
            images = imageUrl;
        }else{
            images = [NSString stringWithFormat:@"%@,%@",images,imageUrl];
        }
    }
    setDickeyobj(requestInfo, images, @"image");
    
    [PPNetworkHelper POST:app_person_complaint_submit parameters:requestInfo success:^(id responseObject) {
        if (YJPPSUCCESS(responseObject)) {
            [AxcUI_Toast AxcUI_showCenterWithText:@"感谢您的反馈"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [AxcUI_Toast AxcUI_showCenterWithText:responseObject[@"msg"]];
        }
    } failure:^(NSError *error) {
        
    } showLoading:self.view];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    mNavitationTitle(@"投诉");
    self.view.backgroundColor = [UIColor whiteColor];
    self.storeNameLabel.text = [AppUserBaseModel sharedUserData].storeName;
    
    self.desTv.placeholderLabel.font = [UIFont systemFontOfSize:14];
    self.desTv.placeholder = @"请输入吐槽意见,您的意见是我们前进的动力";
    self.desTv.backgroundColor = [UIColor AxcUI_colorWithHexCode:@"#ebebeb"];
    self.desTv.placeholderLabel.textAlignment = NSTextAlignmentLeft;
    self.desTv.placeholderFrame = CGRectMake(5, 5, mScreenWidth-40, 20);
    self.desTv.placeholderLabel.textColor = [UIColor AxcUI_colorWithHexCode:@"#B4B4B4"];
    self.desTv.font = [UIFont systemFontOfSize:14];
    self.desTv.maxLength = 100;
    self.desTv.wordNumLabel.hidden = NO;
    self.desTv.showsVerticalScrollIndicator = NO;
    self.desTv.layer.masksToBounds = YES;
    self.desTv.layer.cornerRadius = 5;
    
    self.postImgsURL = [[NSMutableArray alloc]init];
    self.postImageModule.contentMargin = 0;
    self.postImageModule.contentPadding = 15;
    self.postImageModule.itemSpace = 5;
    self.postImageModule.rootVC = self;
    self.postCellHeight = (mScreenWidth-70)/3+20;
    self.postImageModule.maxSelImages = 3;
    self.postImageModule.rootVC = self;
    //3、随时获取新的布局高度
    WS(weakSelf);
    [self.postImageModule observeViewHeight:^(CGFloat value) {
        weakSelf.postCellHeight = value;
        [weakSelf.tableView reloadData];
    }];
    [self.postImageModule observeSelectedMediaArray:^(NSMutableArray<ACMediaModel *> *list) {
        [self updateImages:list];
    }];
    [self.postImageModule observePostExchangeImagesPoszition:^(NSInteger start, NSInteger end) {
        NSDictionary * infoDic = self.postImgsURL[start];
        [self.postImgsURL removeObject:infoDic];
        [self.postImgsURL insertObject:infoDic atIndex:end];
    }];
    [self.postImageModule observeImageDelBlock:^(NSInteger index) {
        [self.postImgsURL removeObjectAtIndex:index];
    }];
}

#pragma mark - Table view data source
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2 ) {
        return self.postCellHeight+10;
    }
    if (indexPath.row ==1 ) {
        return 120;
    }
    if (indexPath.row ==3 ) {
        return mScreenHeight-self.postCellHeight-350;
    }
    return 50;
}

#pragma mark -
#pragma mark - **************** 上传图片
-(void)updateImages:(NSArray *)list
{
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = 1;
    dispatch_async(dispatch_get_main_queue(), ^{
        //回调或者说是通知主线程刷新，
        [self.axcUI_ActivityHUD AxcUI_showWithText:[NSString stringWithFormat:@"正在上传第%ld张图片",self.postImgsURL.count+1] shimmering:YES];
    });
    
    for (int i=0;i<list.count;i++) {
        ACMediaModel * model  = list[i];
        [queue addOperationWithBlock:^{
            NSLog(@"第一个任务");
            //延迟调用
            ImagePostTool * imgesPostTool = [[ImagePostTool alloc]init];
            id obj = [imgesPostTool UpLoadingForInfo:@[@{@"file":UIImageJPEGRepresentation(model.image, 1.0f)}]];
            if ([obj isKindOfClass:[NSDictionary class]]) {
                NSArray * info = obj[@"data"];
                //
                //                [info setObject:info[@"path"] forKey:@"url"];
                //                [info removeObjectForKey:@"path"];
                
                [self.postImgsURL addObjectVerify:info.firstObject];
            }else{
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新，
                [self.axcUI_ActivityHUD AxcUI_updateText:[NSString stringWithFormat:@"正在上传第%ld张图片",self.postImgsURL.count+1] shimmering:NO];
            });
            //取消延迟调用  用来处理一直上传失败
            //            NSLog(@"%@",info);
            if (i == list.count-1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //回调或者说是通知主线程刷新，
                    [self.axcUI_ActivityHUD AxcUI_dismiss];
                    [self.postImageModule.postImageArr addObjectsFromArray:list];
                });
            }
            
        }];
    }
}

-(AxcUI_ActivityHUD *)axcUI_ActivityHUD
{
    if (!_axcUI_ActivityHUD) {
        _axcUI_ActivityHUD = [[AxcUI_ActivityHUD alloc] init];
        _axcUI_ActivityHUD.axcUI_isTheOnlyActiveView = NO;  // 能否点击背景
        _axcUI_ActivityHUD.axcUI_appearAnimationType = AxcActivityHUDAppearAnimationTypeFadeIn;       // 入场风格
        _axcUI_ActivityHUD.axcUI_disappearAnimationType = AxcActivityHUDDisappearAnimationTypeFadeOut; // 出场风格
        _axcUI_ActivityHUD.axcUI_overlayType = AxcActivityHUDOverlayTypeTransparent;    //  背景框的风格
    }
    return _axcUI_ActivityHUD;
}
/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
